"use client";
import React from "react";
import { Toast, ToastTitle, ToastDescription, useToast } from "./toast";

type ToastPlacement = 'top' | 'top right' | 'top left' | 'bottom' | 'bottom left' | 'bottom right';
type ToastOptions = {
  action?: "error" | "warning" | "success" | "info" | "muted";
  variant?: "solid" | "outline";
  duration?: number;
  description?: string;
  placement?:  ToastPlacement;
};

let toastInstance: ReturnType<typeof useToast> | null = null;

function ToastContainer() {
  const toast = useToast();
  
  React.useEffect(() => {
    toastInstance = toast;
  }, [toast]);

  return null;
}

export const toast = {
  show(message: string, options: ToastOptions = {}) {
    const {
      action = "info",
      variant = "solid",
      duration = 3000,
      placement = "top",
      description,
    } = options;
    if (!toastInstance) {
      return;
    }
    toastInstance.show({
      duration,
      placement,
      render: () => (
        <Toast action={action} variant={variant}>
          <ToastTitle>{message}</ToastTitle>
          {description && <ToastDescription>{description}</ToastDescription>}
        </Toast>
      ),
    });
  },

  success(message: string, description?: string) {
    this.show(message, { action: "success", description });
  },

  error(message: string, description?: string) {
    this.show(message, { action: "error", description });
  },

  warning(message: string, description?: string) {
    this.show(message, { action: "warning", description });
  },

  info(message: string, description?: string) {
    this.show(message, { action: "info", description });
  }
};

export { ToastContainer, Toast, ToastTitle, ToastDescription };